<template>
  <div class="container">
    <form @submit="formSubmit">
      <div class="zan-panel">
        <div class="zan-row">
          <div class="city" style="margin:6px;">
            <button :class="city.code == showCodeCity ? 'zan-btn zan-btn--small zan-btn--warn zan-btn--plain':'zan-btn zan-btn--small notOverStyle'" v-for="city in cityData" :key="city.code" :value="city.code" :index="city.index" @click="showCity(city.code)">{{city.title}}-{{city.code}}-{{city.isOver}}</button>
            
            <button class="zan-btn zan-btn--small zan-btn--warn" @click="addCity">添加</button>
          </div>
        </div>
        <div class="zan-row" v-if="isShow">
          <button v-if="city.isOver == false" :class="city.isOver ? 'zan-btn zan-btn--small zan-btn--warn zan-btn--plain':'zan-btn zan-btn--small notOverStyle'" v-for="city in cityAvailable" :key="city.code" :value="city.code" :index="city.index" @click="overShow(null,city,2)">{{city.title}}-{{city.code}}-{{city.isOver}}</button>
          <!-- <checkbox-group class="checkbox-group" name="city">
            <label class="checkbox" v-for="city in cityAvailable" :key="city.code" v-if="city.isOver == false" >
              <checkbox :value="city.code" /> {{city.title}}
            </label>
          </checkbox-group> -->
        </div>
      </div>
      <div class="zan-panel" v-for="(city, cindex) in cityData" :key="cindex" :id="city.code" v-show="city.code == showCodeCity" style="padding-bottom: 60px;">
        <div class="zan-row" v-for="(area, aindex) in city.subCitys" :key="aindex">
          <div class="zan-cell area" :id="area.code">
            <div class="zan-cell__bd">{{area.title}}-{{area.code}}-{{area.isOver}}</div>
            <div class="zan-cell__ft">
              <checkbox-group class="checkbox-group" @change="overShow(city,area,3)">
                <label class="checkbox">
                  <checkbox :value="area.code" :checked="area.isOver" />全选
                </label>
              </checkbox-group>
            </div>
          </div>
          <div class="town" style="margin:5px;display:inline">
            <button @click="overShow(area,town,4)" :class="town.isOver ? 'zan-btn zan-btn--small zan-btn--warn zan-btn--plain':'zan-btn zan-btn--small notOverStyle'" style="margin:3px" v-for="(town,tindex) in area.subCitys" :key="tindex">
              {{town.title}}-{{town.code}}-{{town.isOver}}
            </button>
          </div>
        </div>
        <div class="zan-row">
          <div class="zan-row select-confirm">
            <div class="zan-col zan-col-18 total">
              <span>已选中{{townTotal}}个街道</span>
            </div>
            <div class="zan-col zan-col-6">
              <button class="zan-btn zan-btn--warn" formType="submit">确定</button>
            </div>
          </div>
        </div>
      </div>
    </form>
    <ZanDialog v-bind="zanDialog" />
  </div>

</template>

<script>
import ZanNoticeBar from '../../components/zan/noticebar'
import ZanDialog from '../../components/zan/dialog'
import store from '@/store'
import { workerApi } from '@/api/worker'
import { cityApi } from '@/api/common/cityCode'

export default {
  components: {
    zanbar: ZanNoticeBar,
    ZanDialog
  },
  data() {
    return {
      id: 160,
      showCodeCity: 0, // 设置覆盖区域中，默认显示的市的信息
      isShow: false,
      over: '', // 覆盖区域
      cityAvailable: undefined,
      area: [],
      townTotal: 0,
      isActive: false,
      cityData: [],
      overlayAreaArr:[],
      workerForm: {},
      isOverStyle: {
        // 设置已经覆盖的区域显示的颜色
        margin: '3px',
        color: '#fff7cc',
        backgroundcolor: '#f60'
      },
      notOverStyle: {
        // 设置未覆盖的区域显示的颜色
        margin: '3px',
        color: '#80858a',
        backgroundcolor: '#fff'
      },
      zanDialog: {
        name: '',
        show: false,
        title: '',
        content: '',
        buttons: [],
        buttonsShowVertical: true,
        res: {}
      }
    }
  },
  onShow() {
    this.getWorkerById()
  },
  created() {},
  methods: {
    ...ZanDialog.methods,
    getWorkerById() {
      workerApi.getWorkerById({ id: this.id }).then(res => {
        this.workerForm = res.data
        if (
          this.workerForm.overlayArea !== undefined &&
          this.workerForm.overlayArea !== ''
        ) {
          this.overlayAreaArr = this.workerForm.overlayArea.split(',')
          // 根据工人id查询该工人所覆盖市的信息，并显示在页面上
          workerApi.findOverCitysById({ id: this.id }).then(response => {
            this.setInitStatus(response.data)
            this.cityData = response.data // 查询已经覆盖的市的信息，并以按钮的形式展示在页面上
            this.showCodeCity = this.cityData[this.cityData.length - 1].code // 默认展示地一个市下面的区和乡镇街道
          })
          this.getOverCity() // 获取工人所在省下的所有的市级信息
        } else {
          this.getOverCity() // 获取工人所在省下的所有的市级信息
        }
      })
    },
    setInitStatus(avaCityArr) {
      var count = 0
      for (let i = 0; i < avaCityArr.length; i++) {
        let item = avaCityArr[i]
        item.isOver = this.isOver(item.code)
        if ((item.level == 4 && item.isOver == true) == true) {
          this.townTotal = this.townTotal + 1
        }
        if (item.subCitys != undefined) {
          this.setInitStatus(item.subCitys)
        }
      }
    },
    /**
     * 将选中的覆盖区域的结果统一放入数组中
     */
    overResult(arr, retOver) {
      if (arr != undefined) {
        for (let i = 0; i < arr.length; i++) {
          let city = arr[i]
          if (city.isOver == true) {
            retOver.push(city)
          }
          if (city.subCitys != undefined) {
            this.overResult(city.subCitys, retOver)
          }
        }
      }

      return retOver
    },
    /**
     * 遍历选择的覆盖区域组成的数组，使用逗号分割拼接成字符串，传递给后台
     */
    getOverStr(arr) {
      var over = ''
      var count = 0
      if (arr != undefined) {
        for (let i = 0; i < arr.length; i++) {
          let item = arr[i]
          if (item.level == 4) {
            count = count + 1
          }
          if (i != arr.length - 1) {
            over = over + item.code + ','
          } else {
            over = over + item.code
          }
        }
      }
      this.townTotal = count //统计选中街道的数量
      return over
    },
    overShow(parent, currentCity, currLevel) {
      currentCity.isOver = !currentCity.isOver
      if(currLevel == 2){
        cityApi.findAllSubCitysByParentCode({code:currentCity.code}).then(response => { //根据选择市的code,查询该市的子级，并存入该工人的覆盖区域的集合中
          if(response.code == 0){ //如果查询到市区的子级
            currentCity.subCitys = response.data
            this.setInitStatus(currentCity)
            console.log(this.cityData)
            this.cityData.push(currentCity)
            this.showCodeCity = this.cityData[this.cityData.length - 1].code // 默认展示地一个市下面的区和乡镇街道
            this.isShow = false //选好后将市级可选按钮隐藏
          }
        })
      }
      //如果当前选中为第三级，则子级选择状态同父级的选择状态一直
      if (currLevel == 3) {
        if (currentCity.subCitys != undefined) {
          for (let i = 0; i < currentCity.subCitys.length; i++) {
            let town = currentCity.subCitys[i]
            town.isOver = currentCity.isOver
          }
        }
      }
      //如果当前选中为第四级，则统计父级中，子级被选中的个数，如果全选，则父级别的设置为选中状态，否则设置为未选中状态
      if (currLevel == 4) {
        var count = 0
        for (let i = 0; i < parent.subCitys.length; i++) {
          let sub = parent.subCitys[i]
          if (sub.isOver == true) {
            count = count + 1
          }
        }
        if (count == parent.subCitys.length) {
          parent.isOver = true
        } else {
          parent.isOver = false
        }
      }
      var retOver = []
      this.over = this.getOverStr(this.overResult(this.cityData, retOver))
    },

    /**
     * 点击已经覆盖的市时，动态设置其下的区和乡镇街道的显示
     */
    showCity(cityCode) {
      this.showCodeCity = cityCode
    },
    /**
     * 判断当前code是否已经覆盖，是则返回true,否返回false
     */
    isOver(code) {
      if (this.overlayAreaArr != undefined) {
        if (this.overlayAreaArr.indexOf(code.toString()) != -1) {
          return true
        } else {
          return false
        }
      } else {
        return false
      }
    },
    getOverCity() {
      var province = this.workerForm.province
      if (province != undefined) {
        cityApi.findCitysByParentCode({ code: province }).then(response => {
          if (response.data !== undefined && response.data.length > 0) {
            this.setInitStatus(response.data)
            this.cityAvailable = response.data
          }
        })
      } else {
        const obj = {
          content: '请先设置您的居住地'
        }
        this.showZanDialog(obj).then(() => {
          wx.navigateTo({ url: '../edit/auth' })
        })
      }
    },
    formSubmit: function() {
      workerApi.updateOverById({ id: 160, overlayArea: this.over }).then(res => {
        wx.navigateTo({ url: '../edit/auth' })
      })
    },
    addCity(){
      this.isShow = !this.isShow
    }
  }
}
</script>
<style  scoped>
.zan-panel {
  background: #fff;
  margin-top: 0rpx;
  overflow: hidden;
}
.zan-cell {
  position: relative;
  padding: 20rpx 20rpx;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-align: center;
  align-items: center;
  line-height: 1.4;
  font-size: 28rpx;
  background-color: #f5f5f5;
  color: #777c82;
  height: 20rpx;
}

.town .isOver {
  margin: 3px;
  color: #fff7cc;
  background-color: #f60;
}
.town .unOver {
  margin: 3px;
  color: #80858a;
  background-color: #fff;
}

.isOverStyle {
  /* 设置已经覆盖的区域显示的颜色 */
  margin: 3px;
  color: #f60;
  border-color: #fff7cc;
  /* background-color: #fff7cc; */
}
.notOverStyle {
  /* 设置未覆盖的区域显示的颜色 */
  margin: 3px;
  color: #80858a;
  background-color: #f5f5f5;
}
.total {
  background-color: #f5f5f5;
  color: #777c82;
  text-align: left;
  line-height: 45px;
  font-size: 16px;
}
.select-confirm {
  position: fixed;
  bottom: 0;
  width: 100%;
  background-color: #f5f5f5;
}
.checkbox-group {
  margin-left: 1em;
}
.active {
  width: 40px;
  background-color: green;
}

.unActive {
  width: 40px;
  background-color: red;
}
.green {
  background-color: green;
}
.red {
  background-color: red;
}
</style>
